<template>
  <div class="app-container">
    <div class="filter-container filter-area">
      <!-- Product Name Selection -->
      <label class="filter-item" style="margin-right: 10px;">产品名称:</label>
      <el-select
        v-model="listQuery.prodCode"
        placeholder="请选择产品名称"
        clearable
        style="width: 200px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in productOptions"
          :key="item.prodCode"
          :label="item.prodName"
          :value="item.prodCode"
        />
      </el-select>
    </div>

    <!-- Operation Buttons -->
    <div class="filter-container operation-area">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 8px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加功能
      </el-button>

      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleExport"
      >
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="tableHeight"
      :header-cell-style="{ background: '#fafafa' }"
    >

      <el-table-column label="产品类型" min-width="80px">
        <template slot-scope="{row}">
          <span>{{ row.prdCataName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="80px">
        <template slot-scope="{row}">
          <span>{{ row.prodName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一级功能" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.funcLevelOne }}</span>
        </template>
      </el-table-column>
      <el-table-column label="二级功能" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.funcLevelTwo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="三级功能" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.funcLevelThree }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据要素" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.dataRequire }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.sts!='1'" size="mini" type="danger" @click="handleModifyStatus(row,'1')">
            禁用
          </el-button>
          <el-button v-else size="mini" type="success" @click="handleModifyStatus(row,'0')">
            启用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      class="pagination-container"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="fixed-dialog">
      <div class="dialog-wrapper">
        <div class="dialog-content">
          <el-form
            ref="dataForm"
            :rules="rules"
            :model="temp"
            label-position="left"
            label-width="100px"
            style="width: 600px; margin-left:50px;"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品类型" prop="prdCataCode">
                  <el-select
                    v-model="temp.prdCataCode"
                    placeholder="请选择产品类型"
                  >
                    <el-option
                      v-for="item in productTypeOptions"
                      :key="item.prdCataCode"
                      :label="item.prdCataName"
                      :value="item.prdCataCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="prodCode">
                  <el-select
                    v-model="temp.prodCode"
                    placeholder="请选择产品名称"
                    @change="handleProductChange"
                  >
                    <el-option
                      v-for="item in productOptions"
                      :label="item.prodName"
                      :value="item.prodCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">

              <el-col :span="24">
                <el-form-item label="一级功能" prop="funcLevelOne">
                  <el-input v-model="temp.funcLevelOne" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="一级功能说明" prop="funcDescOne">
                  <el-input v-model="temp.funcDescOne" type="textarea" :rows="4" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">

              <el-col :span="24">
                <el-form-item label="二级功能" prop="funcLevelTwo">
                  <el-input v-model="temp.funcLevelTwo" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="二级功能说明" prop="funcDescTwo">
                  <el-input v-model="temp.funcDescTwo" type="textarea" :rows="4" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">

              <el-col :span="24">
                <el-form-item label="三级功能" prop="funcLevelThree">
                  <el-input v-model="temp.funcLevelThree" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="三级功能说明" prop="funcDescThree">
                  <el-input v-model="temp.funcDescThree" type="textarea" :rows="4" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="数据要素" prop="dataRequire">
                  <el-input v-model="temp.dataRequire" type="textarea" :rows="3" />
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPrdFuncList, exportPrdFuncList, createPrdFunc, updatePrdFunc, deletePrdFunc, changePrdFuncStatus } from '@/api/prd_func'
import { fetchPrdCataList } from '@/api/prd_cata'
import { fetchPrdProdList } from '@/api/prd_prod'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'PrdFunc',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        enabled: 'success',
        disabled: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableHeight: 'calc(100vh - 320px)',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        prodId: ''
      },
      temp: {
        id: undefined,
        prdCataCode: '',
        prdCataName: '',
        prodCode: '',
        prodName: '',
        funcLevelOne: '',
        funcDescOne: '',
        funcLevelTwo: '',
        funcDescTwo: '',
        funcLevelThree: '',
        funcDescThree: '',
        sts: '0',
        stsDesc: '启用',
        dataRequire: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑功能定义',
        create: '创建功能定义'
      },
      rules: {
        prdCataCode: [{ required: true, message: '产品类型不能为空', trigger: 'change' }],
        prodCode: [{ required: true, message: '产品名称不能为空', trigger: 'change' }],
        funcName: [{ required: true, message: '功能名称不能为空', trigger: 'blur' }]
      },
      statusOptions: [
        { key: '0', stsDesc: '启用' },
        { key: '1', stsDesc: '禁用' }
      ],

      productTypeOptions: [], // 确保初始化为空数组
      productOptions: [], // 确保初始化为空数组
      downloadLoading: false
    }
  },
  computed: {
    // 计算属性-动态计算产品类型名称
    computedPrdCataName: function() {
      const selectedOption = this.productTypeOptions.find(option => option.prdCataCode === this.temp.prdCataCode)
      return selectedOption ? selectedOption.prdCataName : ''
    },
    // 计算属性-动态计算产品名称
    computedProdName: function() {
      const selectedOption = this.productOptions.find(option => option.prodCode === this.temp.prodCode)
      return selectedOption ? selectedOption.prodName : ''
    }
  },
  created() {
    this.getList()
    this.getProductTypes()
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)
  },
  mounted() {
    this.observer = new MutationObserver(this.calculateTableHeight)
    this.observer.observe(document.querySelector('.filter-area'), {
      childList: true,
      subtree: true,
      attributes: true
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchPrdFuncList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getProductTypes() {
      fetchPrdCataList({ page: 1, limit: 200 }).then(response => {
        this.productTypeOptions = response.data.items || []

        // When product types are loaded, also load products
        if (this.productTypeOptions.length > 0 && !this.temp.prdCataCode) {
          this.temp.prdCataCode = this.productTypeOptions[0].prdCataCode
          this.handleProductTypeChange(this.temp.prdCataCode)
        }
      })
    },
    getProductsByType(prdCataCode) {
      if (!prdCataCode) {
        this.productOptions = []
        return
      }

      fetchPrdProdList({ prdCataCode: prdCataCode, page: 1, limit: 200 }).then(response => {
        this.productOptions = response.data.items || []
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.sort = 'funcLevelOne:desc,funcLevelTwo:desc'
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        prdCataCode: '',
        prdCataName: '',
        prodCode: '',
        prodName: '',
        sts: '0',
        stsDesc: '启用',
        funcLevel1: '',
        funcDesc1: '',
        funcLevel2: '',
        funcDesc2: '',
        funcLevel3: '',
        funcDesc3: '',
        dataRequire: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleProductTypeChange(value) {
      const selectedType = this.productTypeOptions.find(item => item.prdCataCode === value)
      if (selectedType) {
        this.temp.prdCataName = selectedType.prdCataName
        this.getProductsByType(value)
      } else {
        this.productOptions = []
        this.temp.prodCode = ''
        this.temp.prodName = ''
        this.temp.prdCataName = ''
      }
    },
    handleProductChange(value) {
      // 添加安全检查：确保 productOptions 是数组
      if (!Array.isArray(this.productOptions)) {
        this.temp.prodName = ''
        return
      }
      const selectedProduct = this.productOptions.find(item => item.prodCode === value)
      if (selectedProduct) {
        this.temp.prodName = selectedProduct.prodName
      } else {
        this.temp.prodName = ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 安全检查：确保 productTypeOptions 和 productOptions 是数组
          const selectedProduct = Array.isArray(this.productOptions)
            ? this.productOptions.find(item => item.prodCode === this.temp.prodCode)
            : null

          const submitData = {
            ...this.temp,
            prdCataName: this.computedPrdCataName,
            prodName: this.computedProdName,
            stsDesc: this.computedStsDesc
          }

          createPrdFunc(submitData).then((response) => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '保存成功',
              message: response.data.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()

        // Load product types and products for editing
        if (this.temp.prodType && this.productTypeOptions.length === 0) {
          this.getProductTypes()
        } else if (this.temp.prodType) {
          this.getProductsByType(this.temp.prodType)
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 安全检查：确保 productTypeOptions 和 productOptions 是数组
          const selectedProduct = Array.isArray(this.productOptions)
            ? this.productOptions.find(item => item.prodCode === this.temp.prodCode)
            : null

          const tempData = {
            ...this.temp,
            prdCataName: this.computedPrdCataName,
            prodName: this.computedProdName,
            stsDesc: this.computedStsDesc
          }
          updatePrdFunc(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除该功能定义?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePrdFunc(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },
    handleModifyStatus(row, status) {
      const tempData = {
        id: row.id,
        sts: status,
        stsDesc: status === '0' ? '启用' : '禁用'
      }
      changePrdFuncStatus(tempData).then(() => {
        this.getList()
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleExport() {
      this.downloadLoading = true
      // 构造导出参数，包含当前筛选条件
      const params = {
        ...this.listQuery,
        sort: 'funcLevelOne:desc,funcLevelTwo:desc',
        exportFields: 'prodName:产品名称,prdCataName:产品类型名称'
      }

      // 调用后端导出接口
      exportPrdFuncList(params).then(response => {
        // 检查响应状态码是否为成功
        if (response.status === 200) {
          // 创建下载链接
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '产品功能字典数据.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)

          this.downloadLoading = false
          this.$notify({
            title: '成功',
            message: '导出成功',
            type: 'success',
            duration: 2000
          })
        } else {
          // 如果状态码不是200，提示错误
          this.downloadLoading = false
          this.$message({
            message: '导出失败，请检查网络或联系管理员',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        this.downloadLoading = false
        // 捕获错误并显示详细信息
        console.error('Export error:', error)
        this.$message({
          message: '导出失败，未知异常',
          type: 'error',
          duration: 2000
        })
      })
    },
    calculateTableHeight() {
      const filterHeight = document.querySelector('.filter-area')?.offsetHeight || 0
      const operationHeight = document.querySelector('.operation-area')?.offsetHeight || 0
      const paginationHeight = 60
      const padding = 40

      this.tableHeight = `calc(100vh - ${filterHeight + operationHeight + paginationHeight + padding}px)`
      this.$nextTick(() => {
        this.tableKey++
      })
    }
  }
}
</script>

<style scoped>
</style>
